package com.hqq.exercise.cal;

/**
 * CalCarryBit
 * 题目描述:
 * 计算两个整数相加时需要进行多少次进位
 * 要求程序可以处理多组数据直到读到两个0 假设输入的整数都不超过9个数字
 * Created by heqianqian on 2017/8/8.
 */
public class CalCarryBit {

    public static int calCarryNum(int num1, int num2) {
        if (num1 == 0 && num2 == 0) {
            return -1;
        }
        //每次mod 10就可以取到个位
        int carry = 0;
        int count = 0;
        int temp = 0;
        while (num1 != 0 && num2 != 0) {
            temp = num1 % 10 + num2 % 10 + carry;
            if (temp >= 10) {
                count++;
                carry = temp - 10;
            }
            num1 = (num1-num1%10)/10;
            num2 = (num2-num2%10)/10;
        }
        return count;
    }


    public static int calCarryBit(int num1, int num2) {
        if (num1 == 0 && num2 == 0) {
            return -1;
        }
        int num1Bit = countBit(num1);
        int num2Bit = countBit(num2);
        int temp = Math.min(num1Bit, num2Bit);
        int carry = 0;
        int count = 0;

        for (int i = 0; i < temp; i++) {
            int result = calBitNum(num1, i) + calBitNum(num2, i) + carry;
            if (result >= 10) {
                count++;
                carry = result - 10;
            }
        }
        return count;
    }

    /**
     * 计算一个整数的位数
     */
    public static int countBit(int number) {
        int count = 1;
        int temp = number / 10;
        while (temp != 0) {
            count++;
            temp = temp / 10;
        }
        return count;
    }

    /**
     * 求倒数第(index+1)个数字
     */
    public static int calBitNum(int number, int index) {
        if (index == 0) {//求个位数
            return number % 10;
        } else {
            int num = (int) Math.pow(10, index);
            return number / num % num % 10;
        }
    }

}



